from gameServer import gameServer
from object import Object
from eventServer import eventServer
from textureServer import textureServer
from keys import keys
from copy import copy

from OpenGL.GL import *
from OpenGL import GLUT

import os.path
import yaml

class Menu(Object):
    def __init__(self):
        Object.__init__(self)
        
        self.defaultVar('x',0)
        self.defaultVar('y',0)
        self.defaultVar('w',1)
        self.defaultVar('h',1)
        self.defaultVar('backgroundTexture','menuBackground')
        self.defaultVar("shown",True)
        self.defaultVar("showBackground",True)
        self.defaultVar("highlightWidget",None)
        self.defaultVar("joyButton1",1)
        self.defaultVar("joyButton2",0)
        self.defaultVar("majorAxis",'y')
        self.defaultVar("enableJoyInput",True)
        self.defaultVar("saveState",True)
        
        self.defaultVar("state",{})
        
        eventServer.register('overlayRender',self.renderBackground)
        eventServer.register('joyAxisMotion',self.joyAxisMotion)
            
        functions = ['initMenu','update','overlayRender','mouseButtonUp','mouseButtonDown','mouseMotion','keyUp','keyDown','joyButtonUp','joyButtonDown','joyAxisMotion']
        
        for function in functions:
            eventServer.register(function,self.dispatch)
            
        eventServer.pull('init',{})
        
        self.highlightJoy = None
        self.highlightAxis = None
        self.acceptHighlight = True
        self.blockHighlightAxis = False
        self.highlightPos = 0
        self.highlightWidgets = ['button','slider','spinner','input']
        self.lastNumWidgets = None
        self.sortedWidgets = None
        
    def saveState(self):
        if self.getVar("saveState"):
            filename = 'dat/%s_state.yml' % self.getVar("name")
            print "save", filename
            yaml.dump(self.getVar("state"),open(filename,'w'))
            
    def loadState(self):
        if self.getVar("saveState"):
            filename = 'dat/%s_state.yml' % self.getVar("name")
            if os.path.isfile(filename):
                print "load", filename
                self.getVar("state").update(yaml.load(open(filename)))
        
    def joyAxisMotion(self, cmd, args):
        if not self.getVar("shown") or not self.getVar("enableJoyInput"):
            return
        
        value = args['value']
        joy = args['joy']
        axis = args['axis']
        
        widgets = self.getVar("widgets")
        if widgets and self.acceptHighlight and not self.blockHighlightAxis and abs(value) > 0.5:
            tryCount = 0
            if value < 0:
                incVal = -1
            else:
                incVal = 1
            if not self.getVar("highlightWidget"):
                inc = 0
            else:
                inc = incVal
            found = False
            
            if not self.sortedWidgets or len(widgets) != self.lastNumWidgets:
                self.lastNumWidgets = len(widgets)
                self.sortWidgets()
            
            while not found and tryCount < len(widgets):
                tryCount += 1
                self.highlightPos += inc
                inc = incVal
                widgetName, widgetVals = self.sortedWidgets[self.highlightPos % len(widgets)]
                if widgetVals.has_key('type'):
                    widgetType = widgetVals['type']
                else:
                    widgetType = widgetName.split('_')[0]
                if widgetType in self.highlightWidgets:
                    found = True
                    self.setVar('highlightWidget',widgetName)
                    
                    self.highlightJoy = joy
                    self.highlightAxis = axis
                    self.acceptHighlight = False
                    
        elif joy == self.highlightJoy and axis == self.highlightAxis and abs(value) < 0.5:
            self.acceptHighlight = True
            
    def sortWidgets(self):
        widgetDict = self.getVar("widgets")
        if widgetDict:
            
            eps = 0.01
            requiredVars = ['x','y']
            majorAxis = self.getVar('majorAxis')
            if majorAxis == 'x':
                minorAxis = 'y'
            elif majorAxis == 'y':
                minorAxis = 'x'
            else:
                majorAxis = 'y'
                minorAxis = 'x'
            def comp(w1, w2):
                for var in requiredVars:
                    if not w1[1].has_key(var) or not w2[1].has_key(var):
                        return 0
                    
                if w1[1][majorAxis] < w2[1][majorAxis] - eps:
                    return -1
                elif w1[1][majorAxis] > w2[1][majorAxis] + eps:
                    return 1
                elif w1[1][minorAxis] < w2[1][minorAxis] - eps:
                    return -1
                elif w1[1][minorAxis] > w2[1][minorAxis] + eps:
                    return 1
                else:
                    return 0
                
            self.sortedWidgets = widgetDict.items()
            self.sortedWidgets.sort(comp)
                
    def dispatch(self, cmd, args):
        if cmd == 'initMenu':
            self.setVar('highlightWidget',None)
        
        if self.getVar("shown") and self.vars.has_key('widgets'):
            for widgetName, widgetDictOld in self.vars['widgets'].iteritems():
                widgetDict = copy(widgetDictOld)
                widgetDict['name'] = widgetName
                if widgetDict.has_key('type'):
                    widgetType = widgetDict['type']
                else:
                    widgetType = widgetName.split('_')[0]
                functionName = "%s_%s" % (cmd,widgetType)
                if hasattr(self,functionName) and callable(getattr(self,functionName)):
                    widgetDict['cmd'] = args
                    getattr(self,functionName)(functionName,widgetDict)
                    
                if cmd == 'overlayRender' and widgetName == self.getVar('highlightWidget'):
                    self.renderOverlay(widgetDict)
                    
        if cmd == 'initMenu':
            self.loadState()
                    
    def renderOverlay(self, args):
        ix = self.getArg(args,'x',0)
        iy = self.getArg(args,'y',0)
        iw = self.getArg(args,'w',0)
        ih = self.getArg(args,'h',0)
        
        overlap = 0.1
        px = ix - iw * overlap
        py = iy - ih * overlap
        pw = iw * (1.0 + overlap * 2.0)
        ph = ih * (1.0 + overlap * 2.0)
        
        x,y = self.convertCoordToScreen(px,py)
        w,h = self.convertCoordToScreen(px+pw,py+ph)
        
        glPushMatrix()
        
        glTranslatef(0,0,0.1)
        
        glColor4f(1,0,0,0.1)
        
        glBegin(GL_QUADS)
        
        glVertex2f(x,y)
        glVertex2f(x,h)
        glVertex2f(w,h)
        glVertex2f(w,y)
        
        glEnd()
        
        glColor4f(1,1,1,1)
        
        glPopMatrix()
                        
    def convertAbsCoord(self, x, y):
        return float(x) * gameServer.screenw, float(y) * gameServer.screenh
    
    def convertCoordToScreen(self, x, y):
        nx,ny = self.convertCoord(x,y)
        return self.convertAbsCoord(nx,ny)
    
    def convertCoord(self, x, y):
        nx = self.getVar("x") + float(x) * self.getVar("w")
        ny = self.getVar("y") + float(y) * self.getVar("h")
        return nx,ny
    
    def renderRect(self, px, py, pw, ph, texture):
        x,y = self.convertCoordToScreen(px,py)
        w,h = self.convertCoordToScreen(px+pw,py+ph)
        
        if texture and not textureServer.bindTexture(texture,True):
            return False
        
        glBegin(GL_QUADS)
        
        glTexCoord2f(0,0)
        glVertex2f(x,y)
        glTexCoord2f(0,1)
        glVertex2f(x,h)
        glTexCoord2f(1,1)
        glVertex2f(w,h)
        glTexCoord2f(1,0)
        glVertex2f(w,y)
        
        glEnd()
        
        textureServer.unbindTexture()
        return True
        
    def renderText(self, rx, ry, text, color, font):
        """
            fonts are:
            times_roman_[10|24]
            helvetica_[10|12|18]
        """
        
        x,y = self.convertCoordToScreen(rx,ry)
        
        if not color:
            color = (1,1,1)
            
        glColor3f(color[0],color[1],color[2])
        
        fontName = "GLUT_BITMAP_" + font.upper()
        if GLUT.__dict__.has_key(fontName):
            glutFont = GLUT.__dict__[fontName]
        else:
            glutFont = GLUT.GLUT_BITMAP_HELVETICA_18

        try:            
            height = GLUT.glutBitmapHeight(glutFont)
        except:
            height = 18
        width = 0
        for ch in text:
            width += GLUT.glutBitmapWidth(glutFont,ord(ch))
            
        glPushMatrix()
        
        glTranslatef(0,0,0.01)
        glRasterPos(x-width/2.0,y+height/2.0-5,0)
        
        for ch in text:
            GLUT.glutBitmapCharacter(glutFont,ord(ch))
            
        glPopMatrix()
        
        glColor3f(1,1,1)
        
    def renderBackground(self, cmd, args):
        if self.getVar("shown") and self.getVar("showBackground"):
            glPushMatrix()
            glTranslatef(0,0,-0.01)
            self.renderRect(0,0,1,1,self.getVar("backgroundTexture"))
            glPopMatrix()
        
    def getArg(self, args, name, default):
        if args.has_key(name):
            return args[name]
        elif self.hasVar(name):
            return self.getVar(name)
        else:
            return default
        
    #image widget
    
    def overlayRender_image(self, cmd, args):
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        texture = self.getArg(args,'texture','')
        self.renderRect(x,y,w,h,texture)
        
    #text widget
    
    def overlayRender_text(self, cmd, args):
        x = self.getArg(args,'x',0.5)
        y = self.getArg(args,'y',0.5)
        text = self.getArg(args,'text','')
        color = self.getArg(args,'textColor',(1,1,1))
        font = self.getArg(args,'font','helvetica_18')
        self.renderText(x,y,text,color,font)
        
    #button widget
    
    def initMenu_button(self, cmd, args):
        self.defaultVar(args['name'] + '_active',False)
        
        activeTexture = self.getArg(args,'activeTexture','buttonActive')
        inactiveTexture = self.getArg(args,'inactiveTexture','buttonInactive')
        
        #print "preloading", activeTexture, inactiveTexture
        
        textureServer.bindTexture(activeTexture,True)
        textureServer.bindTexture(inactiveTexture,True)
        textureServer.unbindTexture()
        
    def overlayRender_button(self, cmd, args):
        if self.getVar(args['name'] + '_active'):
            texture = self.getArg(args,'activeTexture','buttonActive')
        else:
            texture = self.getArg(args,'inactiveTexture','buttonInactive')
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        self.renderRect(x,y,w,h,texture)
        textColor = self.getArg(args,'textColor',(1,1,1))
        
        text = self.getArg(args,'text','')
        font = self.getArg(args,'font','helvetica_18')
        self.renderText(x+w/2.0,y+h/2.0,text,textColor, font)
        
    def mouseButtonDown_button(self, cmd, args):
        mousex = args['cmd']['x']
        mousey = args['cmd']['y']
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        x,y = self.convertCoord(x,y)
        w,h = self.convertCoord(w,h)
        activeName = args['name'] + '_active'
        active = self.getVar(activeName)
        
        if not active and mousex > x and mousex < x + w and mousey > y and mousey < y + h:
            self.setVar(activeName,True)
            
    def mouseButtonUp_button(self, cmd, args):
        mousex = args['cmd']['x']
        mousey = args['cmd']['y']
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        x,y = self.convertCoord(x,y)
        w,h = self.convertCoord(w,h)
        activeName = args['name'] + '_active'
        active = self.getVar(activeName)
        
        if active:
            self.setVar(activeName,False)
            if mousex > x and mousex < x + w and mousey > y and mousey < y + h:
                self.sendButton(args)
                    
    def joyButtonDown_button(self, cmd, args):
        if args['name'] == self.getVar("highlightWidget") and args['cmd']['button'] == self.getVar("joyButton1") and self.getVar("enableJoyInput"):
            #print "joy activating button", args['name']
            self.sendButton(args)
                    
    def sendButton(self, args):
        self.saveState()
        
        event = [i.strip() for i in self.getArg(args,'event','').split(',')]
        #print "%s clicked" % args['name']
        for eventStr in event:
            eventArgs = self.getArg(args,'eventArgs',{})
            eventArgs.update(self.getVar("state"))
            eventArgs['buttonName'] = args['name']
            eventServer.pull(eventStr,eventArgs)
                
    #spinner widget
    
    def initMenu_spinner(self, cmd, args):
        #print cmd, args
        
        vals = self.getArg(args,'vals',[None])
        
        self.getVar("state")[args['name']] = vals[0]
        self.defaultVar(args['name'] + '_leftActive',False)
        self.defaultVar(args['name'] + '_rightActive',False)
        
        for val in vals:
            texture = '%s_texture' % str(val)
            if args.has_key(texture):
                textureServer.bindTexture(args[texture],True)
        textureServer.unbindTexture()
        
    def overlayRender_spinner(self, cmd, args):
        val = str(self.getVar("state")[args['name']])
        
        leftActiveName = args['name'] + '_leftActive'
        rightActiveName = args['name'] + '_rightActive'
        leftActive = self.getVar(leftActiveName)
        rightActive = self.getVar(rightActiveName)
        
        if leftActive:
            leftTexture = self.getArg(args,'leftTextureActive','spinnerLeftActive')
        else:
            leftTexture = self.getArg(args,'leftTextureInactive','spinnerLeftInactive')
        if rightActive:
            rightTexture = self.getArg(args,'rightTextureActive','spinnerRightActive')
        else:
            rightTexture = self.getArg(args,'rightTextureInactive','spinnerRightInactive')
        valTexture = self.getArg(args,'%s_texture' % val,val)
        
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        buttonw = self.getArg(args,'buttonw',0.25) * w
        centerw = w - buttonw * 2.0
        textColor = self.getArg(args,'textColor',(1,1,1))
        
        self.renderRect(x,y,buttonw,h,leftTexture)
        if valTexture:
            self.renderRect(x+buttonw,y,centerw,h,valTexture)
        self.renderRect(x+buttonw+centerw,y,buttonw,h,rightTexture)
        
        showText = self.getArg(args,'showText',True)
        if showText:
            font = self.getArg(args,'font','helvetica_18')
            self.renderText(x+w/2.0,y+h/2.0,val,textColor,font)
        
    def mouseButtonDown_spinner(self, cmd, args):
        mousex = args['cmd']['x']
        mousey = args['cmd']['y']
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        buttonw = self.getArg(args,'buttonw',0.25) * w
        centerw = w - buttonw * 2.0
        
        leftx, lefty = self.convertCoord(x,y)
        leftw, lefth = self.convertCoord(buttonw,h)
        rightx, righty = self.convertCoord(x+buttonw+centerw,y)
        rightw, righth = self.convertCoord(buttonw,h)
        
        leftActiveName = args['name'] + '_leftActive'
        rightActiveName = args['name'] + '_rightActive'
        leftActive = self.getVar(leftActiveName)
        rightActive = self.getVar(rightActiveName)
        
        if not leftActive and mousex > leftx and mousex < leftx + leftw and mousey > lefty and mousey < lefty + lefth:
            self.setVar(leftActiveName,True)
        if not rightActive and mousex > rightx and mousex < rightx + rightw and mousey > righty and mousey < righty + righth:
            self.setVar(rightActiveName,True)

    def mouseButtonUp_spinner(self, cmd, args):
        mousex = args['cmd']['x']
        mousey = args['cmd']['y']
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        buttonw = self.getArg(args,'buttonw',0.25) * w
        centerw = w - buttonw * 2.0
        
        leftx, lefty = self.convertCoord(x,y)
        leftw, lefth = self.convertCoord(buttonw,h)
        rightx, righty = self.convertCoord(x+buttonw+centerw,y)
        rightw, righth = self.convertCoord(buttonw,h)
        
        leftActiveName = args['name'] + '_leftActive'
        rightActiveName = args['name'] + '_rightActive'
        leftActive = self.getVar(leftActiveName)
        rightActive = self.getVar(rightActiveName)
        
        vals = self.getArg(args,'vals',[None])
        val = self.getVar("state")[args['name']]
        valPos = vals.index(val)
        
        if leftActive:
            self.setVar(leftActiveName,False)
            if mousex > leftx and mousex < leftx + leftw and mousey > lefty and mousey < lefty + lefth:
                self.getVar("state")[args['name']] = vals[(valPos-1)%len(vals)]

        if rightActive:
            self.setVar(rightActiveName,False)
            if mousex > rightx and mousex < rightx + rightw and mousey > righty and mousey < righty + righth:
                self.getVar("state")[args['name']] = vals[(valPos+1)%len(vals)]
                
    def joyButtonDown_spinner(self, cmd, args):
        if args['name'] == self.getVar('highlightWidget') and self.getVar("enableJoyInput"):
            button = args['cmd']['button']
            vals = self.getArg(args,'vals',[None])
            val = self.getVar("state")[args['name']]
            valPos = vals.index(val)
        
            if button == self.getVar("joyButton1"):
                self.getVar("state")[args['name']] = vals[(valPos+1)%len(vals)]
            elif button == self.getVar("joyButton2"):
                self.getVar("state")[args['name']] = vals[(valPos-1)%len(vals)]
                
    #slider widget
    
    def initMenu_slider(self, cmd, args):
        minVal = self.getArg(args,'minVal',0.0)
        maxVal = self.getArg(args,'maxVal',0.0)
        self.getVar('state')[args['name']] = (minVal + maxVal) / 2.0
        
        self.defaultVar(args['name'] + '_active',False)
        
    def overlayRender_slider(self, cmd, args):
        val = self.getVar('state')[args['name']]
        minVal = self.getArg(args,'minVal',0.0)
        maxVal = self.getArg(args,'maxVal',1.0)
        propVal = (val - minVal) / float(maxVal - minVal)
        
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        
        active = self.getVar(args['name'] + '_active')
        
        buttonw = self.getArg(args,'buttonw',0.1) * w
        buttonh = self.getArg(args,'buttonh',1.0) * h/2.0
        buttonx = x + propVal * w - buttonw/2.0
        buttony = y + h/2.0
        if active:
            buttonTexture = self.getArg(args,'buttonActiveTexture','buttonActive')
        else:
            buttonTexture = self.getArg(args,'buttonInactiveTexture','buttonInactive')
        
        railh = self.getArg(args,'railh',0.1) * h
        railTexture = self.getArg(args,'railTexture','sliderRailTexture')
        
        self.renderRect(x,y+h*0.75-railh/2.0,w,railh,railTexture)
        glPushMatrix()
        glTranslatef(0,0,0.01)
        self.renderRect(buttonx, buttony, buttonw, buttonh, buttonTexture)
        glPopMatrix()
        
        textColor = self.getArg(args,'textColor',(1,1,1))
        prefix = self.getArg(args,'prefix',args['name'][args['name'].find('_')+1:])
        text = '%s: %.1f' % (prefix, val)
        font = self.getArg(args,'font','helvetica_18')
        self.renderText(x+w/2.0,y+h/4.0,text,textColor,font)
        
    def mouseButtonDown_slider(self, cmd, args):
        val = self.getVar('state')[args['name']]
        minVal = self.getArg(args,'minVal',0.0)
        maxVal = self.getArg(args,'maxVal',1.0)
        propVal = (val - minVal) / float(maxVal - minVal)
        
        mousex = args['cmd']['x']
        mousey = args['cmd']['y']
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        
        buttonw = self.getArg(args,'buttonw',0.1) * w
        buttonh = self.getArg(args,'buttonh',1.0) * h/2.0
        buttonx = x + propVal * w - buttonw/2.0
        buttony = y + h/2.0
        
        buttonw, buttonh = self.convertCoord(buttonw,buttonh)
        buttonx, buttony = self.convertCoord(buttonx,buttony)
        
        activeName = args['name'] + '_active'
        active = self.getVar(activeName)
        
        if not active and mousex > buttonx and mousex < buttonx + buttonw and mousey > buttony and mousey < buttony + buttonh:
            self.setVar(activeName,True)

    def mouseButtonUp_slider(self, cmd, args):
        activeName = args['name'] + '_active'
        active = self.getVar(activeName)
        
        if active:
            self.setVar(activeName,False)
                
    def mouseMotion_slider(self, cmd, args):
        if not self.getVar(args['name'] + '_active'):
            return
        
        mousex = args['cmd']['x']
        mousey = args['cmd']['y']
        
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        
        x,y = self.convertCoord(x,y)
        w,h = self.convertCoord(w,h)
        
        minVal = self.getArg(args,'minVal',0.0)
        maxVal = self.getArg(args,'maxVal',1.0)
        
        val = minVal + (max(x,min(x+w,mousex)) - x) / float(w) * (maxVal - minVal)
        val = min(maxVal,max(minVal,val))
        self.getVar('state')[args['name']] = val
        
    def joyButtonDown_slider(self, cmd, args):
        if args['name'] == self.getVar("highlightWidget") and args['cmd']['button'] == self.getVar("joyButton1") and self.getVar("enableJoyInput"):
            self.blockHighlightAxis = not self.blockHighlightAxis
            
    def joyAxisMotion_slider(self, cmd, args):
        if self.blockHighlightAxis and args['cmd']['axis']:
            value = args['cmd']['value']
            if abs(value) > 0.5:
                if value < 0:
                    value += 0.5
                else:
                    value -= 0.5
                val = self.getVar('state')[args['name']]
                minVal = self.getArg(args,'minVal',0.0)
                maxVal = self.getArg(args,'maxVal',1.0)
                self.getVar('state')[args['name']] = min(maxVal,max(minVal,val + value/10.0))
        
    #input widget    
    
    def initMenu_input(self, cmd, args):
        self.defaultVar(args['name'] + '_buttonActive', False)
        self.defaultVar(args['name'] + '_waiting', False)
        self.getVar('state')[args['name']] = None
        
    def overlayRender_input(self, cmd, args):
        if self.getVar(args['name'] + '_waiting'):
            val = 'Press...'
        else:
            val = self.getVar('state')[args['name']]
        
        if self.getVar(args['name'] + '_buttonActive'):
            buttonTexture = self.getArg(args,'buttonActiveTexture','buttonActive')
        else:
            buttonTexture = self.getArg(args,'buttonInactiveTexture','buttonInactive')
        
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        buttonText = self.getArg(args,'buttonText','Set Input')
        textColor = self.getArg(args,'textColor',(1,1,1))
        
        self.renderRect(x,y,w,h/2.0,buttonTexture)
        font = self.getArg(args,'font','helvetica_18')
        self.renderText(x+w/2.0,y+h/4.0,buttonText,textColor,font)
        
        self.renderText(x+w/2.0,y+h*0.75,str(val),textColor,font)
        
    def mouseButtonDown_input(self, cmd, args):
        mousex = args['cmd']['x']
        mousey = args['cmd']['y']
        
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        
        x,y = self.convertCoord(x,y)
        w,h = self.convertCoord(w,h/2.0)
        
        buttonActiveName = args['name'] + '_buttonActive'
        buttonActive = self.getVar(buttonActiveName)
        
        if not buttonActive:
            
            waitingName = args['name'] + '_waiting'
            if self.getVar(waitingName):
                
                button = args['cmd']['button']
                self.getVar('state')[args['name']] = 'mouseButton_%d' % button
                self.setVar(waitingName,False)
                self.blockHighlightAxis = False
                
            elif mousex > x and mousex < x + w and mousey > y and mousey < y + h:
                self.setVar(buttonActiveName,True)
                
    def mouseButtonUp_input(self, cmd, args):
        mousex = args['cmd']['x']
        mousey = args['cmd']['y']
        
        x = self.getArg(args,'x',0)
        y = self.getArg(args,'y',0)
        w = self.getArg(args,'w',1)
        h = self.getArg(args,'h',1)
        
        x,y = self.convertCoord(x,y)
        w,h = self.convertCoord(w,h/2.0)
        
        buttonActiveName = args['name'] + '_buttonActive'
        buttonActive = self.getVar(buttonActiveName)
        
        #print cmd, args
        
        if buttonActive:
            self.setVar(buttonActiveName,False)
            
            if mousex > x and mousex < x + w and mousey > y and mousey < y + h:
                waitingName = args['name'] + '_waiting'
                self.setVar(waitingName,True)
                
    def keyDown_input(self, cmd, args):
        waitingName = args['name'] + '_waiting'
        if self.getVar(waitingName):
            self.setVar(waitingName,False)
            
            key = args['cmd']['key']
            keyName = 'key_%d' % key
            for dictKeyName, val in keys.iteritems():
                if val == key:
                    keyName = 'key_%s' % dictKeyName
            
            self.getVar('state')[args['name']] = keyName
            
    def joyButtonDown_input(self, cmd, args):
        waitingName = args['name'] + '_waiting'
        if self.getVar(waitingName):
            self.setVar(waitingName,False)
            
            buttonName = 'joyButton_%d_%d' % (args['cmd']['joy'],args['cmd']['button'])
            self.getVar('state')[args['name']] = buttonName
            self.blockHighlightAxis = False
            
        elif args['name'] == self.getVar("highlightWidget") and args['cmd']['button'] == self.getVar("joyButton1") and self.getVar("enableJoyInput"):
            self.setVar(waitingName,True)
            self.blockHighlightAxis = True
            
    def joyAxisMotion_input(self, cmd, args):
        waitingName = args['name'] + '_waiting'
        if self.getVar(waitingName):
            
            value = args['cmd']['value']
            if abs(value) > 0.5:
                self.setVar(waitingName,False)
                if value < 0:
                    tag = 'neg'
                    value *= -1
                else:
                    tag = 'pos'
                joy = args['cmd']['joy']
                axis = args['cmd']['axis']
                axisName = 'joyAxis_%s_%d_%d' % (tag,joy,axis)
                self.getVar('state')[args['name']] = axisName
                self.blockHighlightAxis = False
                self.highlightJoy = joy
                self.highlightAxis = axis
                self.acceptHighlight = False
